﻿
using Castle.Core.Internal;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_SaleTargetInterfaceBusiness : Interface_BaseBusiness, IAttachment_Business, IJob_Business, ITransientDependency
    {

        public List<OL_FilterDTO> Filters;

        public Base_InterfaceOption queryOption { get; set; }

        public OL_SaleTargetInterfaceBusiness()
        {
            this.InterfaceName = "销售月度目标";
            //字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            //indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();
            Filters.Add(
                 new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value ="" }//F_MO_APPROVEDATE字段过滤单日开始700天前到现在的数据
             );

            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置


            //查询执行中的事件
            OnQueryEvent += Interface_Business_OnQueryEvent; ;
            //查询执行前的事件
            BeforeQueryEvent += Interface_Business_BeforeQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += Interface_Business_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void Interface_Business_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }
        }


        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 新增更新表
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                GetAttachmentList();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }

        /// <summary>
        /// 获取附件列表
        /// </summary>
        public async Task<List<AttaInfo>> GetAttachmentList()
        {
            List<AttaInfo> attasList = new List<AttaInfo>();
            //获取目标数据
            List<NewPrd> targetData = new List<NewPrd>();//目标据集合
            //查询条件
            Filters.Clear();
            Filters.Add(
                new OL_FilterDTO() { ControlId = "utime", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") }
            );

            // Keys.Where(x => x.Type == "A").ForEach(x =>
            // {
            //     //文件，并且，不为空
            //     Filters.Add(
            //    new OL_FilterDTO() { ControlId = x.TField, DataType = 14, SpliceType = 2, FilterType = 8, Value = "" }
            //);
            // });
            targetData = await QueryAsync<NewPrd>(queryOption, tableField, SqlDb);
            //将数据转换成文件列表
            foreach (var item in targetData)
            {
                string rowTitle = item.RowId+"_"+ item.OrderNum;
                List<AttaInfo> a = GetAttaInfo<NewPrd>(item, rowTitle);
                attasList.AddRange(a);
            }
            return attasList;
        }


        /// <summary>
        /// 根据泛型对象获取附件列表信息
        /// </summary>
        /// <typeparam name="T">源数据对象</typeparam>
        /// <param name="t">附件</param>
        /// <param name="rowTitle">附件行标题</param>
        /// <returns></returns>
        public List<AttaInfo> GetAttaInfo<T>(T t,string rowTitle)
        {
            List<AttaInfo> attaList = new List<AttaInfo>();
            foreach (var item1 in Keys)
            {
                //类型为A--附件的才进行处理
                if (item1.Type == "A")
                {
                    var list = t.GetPropertyValue(item1.Field);
                    //获取的文件列表不为空或null
                    if (!list.IsNullOrEmpty())
                    {
                        //转换成ONE_LINK的附件格式
                        List<Attachment> oL_att = JsonConvert.DeserializeObject<List<Attachment>>(list.ToString());
                        foreach (var att in oL_att)
                        {
                            AttaInfo attaInfo = new AttaInfo();
                            attaInfo.FileName = att.original_file_name;
                            attaInfo.Path = this.InterfaceName+@"\" + rowTitle + @"\" + item1.Note;//表名称+行ID_行+列名称
                            attaInfo.FullPath = attaInfo.Path+@"\"+ attaInfo.FileName;
                            attaInfo.Size = att.file_size;
                            attaInfo.Url = att.original_file_full_path;
                            attaInfo.CreateTime = att.createTime;
                            attaList.Add(attaInfo);
                        }
                    }
                }

            }



            return attaList;
        }
    }



}
